package gui

import (
	"log"
	"wxp2p/clientN"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

var remoteClient = clientN.NewClientClient("", "")
var panel = container.NewVBox()

func portMapWindow(gVars *GlobalVars) fyne.CanvasObject {
	// 远程主机
	rCliId := binding.NewString()
	linkBtn := widget.NewButtonWithIcon("连接", theme.LoginIcon(), func() {
		if remoteClient != nil {
			remoteClient.StopRun()
		}
		clId, _ := rCliId.Get()
		remoteClient.ClientId = clId
		remoteClient.ServerAddr = gVars.signalAddr
		remoteClient.Run()
	})
	newBtn := widget.NewButtonWithIcon("增加端口", theme.ContentAddIcon(), func() {
		panel.Add(newHostPortRow(gVars))
	})
	remoteClient.OnStatusChange(func(log string) {
		if log == "ok" {
			linkBtn.Disabled()
			linkBtn.Text = "已连接"
		} else {
			linkBtn.Enable()
			linkBtn.Text = "连接"
		}
	})
	remoteClientIdRow := container.NewBorder(nil, nil, canvas.NewText("远程主机", nil), container.NewHBox(linkBtn, newBtn), widget.NewEntryWithData(rCliId))
	header := container.NewBorder(nil, nil, nil, container.NewHBox(canvas.NewText("    ", nil), canvas.NewText("操作", nil)), container.NewGridWithColumns(4, canvas.NewText("远端IP", nil),
		canvas.NewText("端口", nil), canvas.NewText("本机IP", nil), canvas.NewText("端口", nil)))
	panel.Add(remoteClientIdRow)
	panel.Add(header)

	return panel
}

func newHostPortRow(gVars *GlobalVars) fyne.CanvasObject {
	// 端口映射
	row := container.NewVBox()
	rHost := binding.NewString()
	rHost.Set("127.0.0.1")
	rPort := binding.NewString()
	rPort.Set("80")
	lHost := binding.NewString()
	lHost.Set("127.0.0.1")
	lPort := binding.NewString()
	lPort.Set("80")
	mapBtn := widget.NewButton("映射", func() {
		if remoteClient != nil {
			rH, _ := rHost.Get()
			rP, _ := rPort.Get()
			lH, _ := lHost.Get()
			lP, _ := lPort.Get()
			log.Println(rH, rP, lH, lP)
			remoteClient.CreateDataChannel(rH, rP, lH, lP)
		}
	})
	removeBtn := widget.NewButtonWithIcon("", theme.DeleteIcon(), func() {
		panel.Remove(row)
	})
	content := container.NewBorder(nil, nil, nil, container.NewHBox(mapBtn, removeBtn), container.NewGridWithColumns(4, widget.NewEntryWithData(rHost), widget.NewEntryWithData(rPort), widget.NewEntryWithData(lHost), widget.NewEntryWithData(lPort)))
	row.Add(content)
	return row
}
